package com.wish.g04.base.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wish.g04.base.dto.CustomDTO;
import com.wish.g04.base.dto.JrFactoringDTO;
import com.wish.g04.base.entity.*;
import com.wish.g04.base.mapper.JrFactoringMapper;
import com.wish.g04.base.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wish.g04.base.vo.FactoringDetailVO;
import com.wish.g04.common.security.utils.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/**
 * <p>
 * 租约保理申请表 服务实现类
 * </p>
 *
 * @author 薛凯
 * @since 2022-05-23
 */
@Service
public class JrFactoringServiceImpl extends ServiceImpl<JrFactoringMapper, JrFactoring> implements IJrFactoringService {

    @Autowired
    private ICfContractService iCfContractService;
    @Autowired
    private IJrProductService iJrProductService;
    @Autowired
    private ICwReceiptPlanService iCwReceiptPlanService;
    @Autowired
    private IJrFactoringDetailService iJrFactoringDetailService;
    @Autowired
    private IFkBusinessCreditService iFkBusinessCreditService;
    @Autowired
    private IFkBusinessCreditSubService businessCreditSubService;

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean addJrFactoring(JrFactoringDTO jrFactoringDTO) {
        QueryWrapper<CwReceiptPlan> wrapper = new QueryWrapper<>();
        wrapper.eq("contract_id",jrFactoringDTO.getContractId());
        AtomicReference<Long> businessId = new AtomicReference<>();
        iCwReceiptPlanService.list(wrapper).forEach(item->{
            businessId.set(item.getBusinessId());
        });
        QueryWrapper<FkBusinessCredit> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("business_id",businessId);
        // 根据商户id查询风控主表
        FkBusinessCredit business = iFkBusinessCreditService.getOne(queryWrapper);
        // 查询商户是否授权
        CustomDTO customDTO = businessCreditSubService.selectCustom(jrFactoringDTO);
        // 未授权
        if (customDTO == null ) {
            return false;
        }
        // 可用授信额度
        BigDecimal subtractProduct = BigDecimal.ZERO;
        // 如果已用授信额度不为空 且不为 0
        if (customDTO.getUsedCreditline() != null && !customDTO.getUsedCreditline().equals(BigDecimal.ZERO)) {
            subtractProduct  = customDTO.getTotalCreditline().subtract(customDTO.getUsedCreditline());
        }else {
            subtractProduct = customDTO.getTotalCreditline();
        }
        // 如果应收租金大于可用额度 则不允许
        if (jrFactoringDTO.getRentMoney().compareTo(subtractProduct) == 1) {
            return false;
        }
        // 判断月总额度
        if (customDTO.getMonthlyTotalCreditline() != null && !customDTO.getMonthlyTotalCreditline().equals(BigDecimal.ZERO)) {
            BigDecimal subtractMonthly = BigDecimal.ZERO;
            // 判断月度总额度剩余
            if (customDTO.getMonthlyUsedCreditline() != null && !customDTO.getMonthlyUsedCreditline().equals(BigDecimal.ZERO)) {
                subtractMonthly = customDTO.getMonthlyTotalCreditline().subtract(customDTO.getMonthlyUsedCreditline());
            } else {
                subtractMonthly = customDTO.getMonthlyTotalCreditline();
            }
            // 如果分期额度大于该商户本月可用额度
            if (jrFactoringDTO.getRentMoney().compareTo(subtractMonthly) == 1) {
                return false;
            }
        }else{
            if (business.getHlMonthlyTotalCreditline() != null && !business.getHlMonthlyTotalCreditline().equals(BigDecimal.ZERO)) {
                //商户月授信额度减月已用授信额度
                BigDecimal subtractMonthly = BigDecimal.ZERO;
                if(business.getHlMonthlyUsedCreditline() != null && !business.getHlMonthlyUsedCreditline().equals(BigDecimal.ZERO)) {
                    subtractMonthly = business.getHlMonthlyTotalCreditline().subtract(business.getHlMonthlyUsedCreditline());
                } else {
                    subtractMonthly = business.getHlMonthlyTotalCreditline();
                }
                //申请分期金额大于该商户月剩余授信金额
                if(jrFactoringDTO.getRentMoney().compareTo(subtractMonthly) == 1) {
                    return false;
                }
            }
        }
        // 计算海联使用的额度
        BigDecimal hlUsedCreditline = BigDecimal.ZERO;
        // 海联已使用额度不为空
        if (business.getHlUsedCreditline() != null && !business.getHlUsedCreditline().equals(BigDecimal.ZERO)) {
            hlUsedCreditline = business.getHlUsedCreditline().add(jrFactoringDTO.getRentMoney());
        }else{
            hlUsedCreditline = jrFactoringDTO.getRentMoney();
        }
        // 为风控主表设置 海联额度使用的数量
        business.setHlUsedCreditline(hlUsedCreditline);

        // 判断海联月额度总额度是否为空
        if (business.getHlMonthlyTotalCreditline() != null && !business.getHlMonthlyTotalCreditline().equals(BigDecimal.ZERO)) {
            // 计算海联剩余月额度
            BigDecimal hlMonthlyUsedCreditline = BigDecimal.ZERO;
            if (business.getHlMonthlyUsedCreditline() != null && !business.getHlMonthlyUsedCreditline().equals(BigDecimal.ZERO)) {
                hlMonthlyUsedCreditline = business.getHlMonthlyUsedCreditline().add(jrFactoringDTO.getRentMoney());
            } else {
                hlMonthlyUsedCreditline = jrFactoringDTO.getRentMoney();
            }
        }
        // 为风控主表设置月度已使用额度
        business.setHlMonthlyUsedCreditline(hlUsedCreditline);
        iFkBusinessCreditService.saveOrUpdate(business);

        // 风控字表
        FkBusinessCreditSub fkBusinessCreditSub = new FkBusinessCreditSub();
        BeanUtils.copyProperties(customDTO,fkBusinessCreditSub);
        // 风控字表 已使用的授信额度
        BigDecimal usedCreditlineProduct = BigDecimal.ZERO;
        if (customDTO.getUsedCreditline() != null && !customDTO.getUsedCreditline().equals(BigDecimal.ZERO)) {
            usedCreditlineProduct = customDTO.getUsedCreditline().add(jrFactoringDTO.getRentMoney());
        }else{
            usedCreditlineProduct = jrFactoringDTO.getRentMoney();
        }
        // 为风控字表设置月度已用额度
        fkBusinessCreditSub.setUsedCreditline(usedCreditlineProduct);
        if (customDTO.getMonthlyTotalCreditline() != null && !customDTO.getMonthlyTotalCreditline().equals(BigDecimal.ZERO)) {
            BigDecimal hlMonthlyUsedCreditline = BigDecimal.ZERO;
            if(customDTO.getMonthlyUsedCreditline() != null && !customDTO.getMonthlyUsedCreditline().equals(BigDecimal.ZERO)) {
                hlMonthlyUsedCreditline = customDTO.getMonthlyUsedCreditline().add(jrFactoringDTO.getRentMoney());
            } else {
                hlMonthlyUsedCreditline = jrFactoringDTO.getRentMoney();
            }
            fkBusinessCreditSub.setMonthlyUsedCreditline(hlMonthlyUsedCreditline);
        }
        // 添修改风控子表
        businessCreditSubService.saveOrUpdate(fkBusinessCreditSub);

        // 添加租约保理申请表
        JrFactoring jrFactoring = new JrFactoring();
        BeanUtils.copyProperties(jrFactoringDTO,jrFactoring);
        // 租约保理申请单号
        long snowflakeNextId = IdUtil.getSnowflakeNextId();
        jrFactoring.setFactoringOrderNo("ZYBL"+snowflakeNextId);
        // 金融产品信息
        JrProduct jrProduct = iJrProductService.getById(jrFactoring.getJrProductId());
        // 设置资方信息
        jrFactoring.setCapitalId(jrProduct.getCompanyId());
        jrFactoring.setCapitalName(jrProduct.getCompanyName());
        // 借款总金额 = 授信金额合计
        jrFactoring.setLoanAmount(jrFactoringDTO.getFactoringCreditMoney());

        // 设置申请状态为申请中
        jrFactoring.setApplyState(1);

        // 公共信息
        jrFactoring.setDelFlg(false);
        jrFactoring.setCreateTime(LocalDateTime.now());
        jrFactoring.setCreateUserid(SecurityUtils.getUserId());
        jrFactoring.setUpdateTime(LocalDateTime.now());
        jrFactoring.setUpdateUserid(SecurityUtils.getUserId());
        // 保存
        boolean save = save(jrFactoring);
        if (!save) {
            return save;
        }

        // 申请保理明细
        List<FactoringDetailVO> factoringDetailList = jrFactoringDTO.getFactoringDetailList();
        if (factoringDetailList != null) {
            for (FactoringDetailVO detailVO : factoringDetailList) {
                JrFactoringDetail jrFactoringDetail = new JrFactoringDetail();
                BeanUtils.copyProperties(jrFactoringDetail,detailVO);
                // 设置申请主表id(外键)
                jrFactoringDetail.setFactoringId(jrFactoring.getId());
                // 设置商户id
                jrFactoringDetail.setBusinessId(jrFactoring.getBusinessId());
                // 公共信息
                jrFactoringDetail.setDelFlg(false);
                jrFactoringDetail.setCreateTime(LocalDateTime.now());
                jrFactoringDetail.setCreateUserid(SecurityUtils.getUserId());
                jrFactoringDetail.setUpdateTime(LocalDateTime.now());
                jrFactoringDetail.setUpdateUserid(SecurityUtils.getUserId());
                //保存详细表
                iJrFactoringDetailService.saveOrUpdate(jrFactoringDetail);

                // 冻结合同 添加金融标识
                CfContract cfContract = iCfContractService.getById(jrFactoringDetail.getCfContractId());
                // 冻结
                cfContract.setFreezeStatus(true);
                // 公共信息
                cfContract.setZyblFlg(true);
                cfContract.setUpdateTime(LocalDateTime.now());
                cfContract.setUpdateUserid(SecurityUtils.getUserId());
                // 修改合同
                iCfContractService.saveOrUpdate(cfContract);
            }
        }
        return true;
    }
}

